<template>
  <div v-if="isOwner" class="add-candidate">
    <h3 class="title">👤 添加候选人（仅管理员可见）</h3>

    <form @submit.prevent="addCandidate" class="form">
      <input
        v-model="newName"
        placeholder="请输入候选人姓名"
        :disabled="loading"
        required
      />
      <button type="submit" class="btn" :disabled="loading">
        {{ loading ? '添加中...' : '添加' }}
      </button>
    </form>

    <div v-if="addMsg" :class="['msg', addMsg.includes('成功') ? 'success' : 'error']">
      {{ addMsg }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ethers } from 'ethers';
import { getContract } from '../utils/contract';

const isOwner = ref(false);
const newName = ref('');
const addMsg = ref('');
const loading = ref(false);
const userAddress = ref('');

onMounted(async () => {
  if (window.ethereum) {
    const accounts = await window.ethereum.request({ method: 'eth_accounts' });
    userAddress.value = accounts[0] || '';
    if (userAddress.value) {
      const provider = new ethers.BrowserProvider(window.ethereum);
      const contract = getContract(provider);
      const owner = await contract.owner();
      isOwner.value = userAddress.value.toLowerCase() === owner.toLowerCase();
    }
  }
});

async function addCandidate() {
  addMsg.value = '';
  loading.value = true;
  try {
    const provider = new ethers.BrowserProvider(window.ethereum);
    const signer = await provider.getSigner();
    const contract = getContract(signer);
    const tx = await contract.addCandidate(newName.value);
    addMsg.value = '⏳ 添加中，等待链上确认...';
    await tx.wait();
    addMsg.value = '✅ 添加成功！';
    newName.value = '';
  } catch (e) {
    addMsg.value = '❌ ' + (e.info?.error?.message || e.message || '添加失败');
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.add-candidate {
  background: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #2c3e50;
}

.form {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.form input {
  flex: 1;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 14px;
}

.btn {
  background-color: #3498db;
  color: white;
  padding: 10px 18px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.btn:hover:enabled {
  background-color: #2980b9;
}

.msg {
  margin-top: 12px;
  font-size: 14px;
}

.success {
  color: #2ecc71;
}

.error {
  color: #e74c3c;
}
</style>
